/*
 * author      : dormi330
 * date        : 2018/6/26
 * description : 审核操作
 */

package com.deep.trade.application.order;

import com.deep.trade.adaptor.required.SellerMgmtService;
import com.deep.trade.common.CommonUtils;
import com.deep.trade.common.TradeException;
import com.deep.trade.domain.order.OrderRepository;
import com.deep.trade.domain.order.TradeOrder;
import com.deep.trade.order.dto.InDtoAuditOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AuditOrderService {
    private static final int ONLY_ONE_SHOULD_BE_UPDATED = 1;
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    private OrderRepository orderRepository;
    private SellerMgmtService sellerMgmtService;
    private OrderQueryService orderQueryService;

    @Autowired
    public AuditOrderService(
            OrderRepository orderRepository
            , SellerMgmtService sellerMgmtService
            , OrderQueryService orderQueryService
    ) {
        this.orderRepository = orderRepository;
        this.sellerMgmtService = sellerMgmtService;
        this.orderQueryService = orderQueryService;
    }


    /**
     * 审核一个订单, 无须事务控制
     *
     * @param inDtoAuditOrder 入参
     */
    @Transactional
    public void auditTradeOrder(InDtoAuditOrder inDtoAuditOrder) throws Exception {
        logger.info("{}, {}", CommonUtils.currentClassAndMethod(), inDtoAuditOrder);

        // ====== public 入参检测 =======
        if (null == inDtoAuditOrder || null == inDtoAuditOrder.getTradeOrderId())
            throw new TradeException("tradeOrderId cannot be null");

        // ====== 获取领域对象 =======
        TradeOrder tradeOrder = orderQueryService.assureTradeOrder(inDtoAuditOrder.getTradeOrderId());

        // ====== 权限检测 =======
        logger.error("TODO 检验当前用户有权限进行 订单审核");
        boolean canAudit = sellerMgmtService.canUserAuditOrder(tradeOrder.getSellerId());
        if (!canAudit) throw new Error("cannot auditOne this order");

        // ====== 领域对象操作 =======
        tradeOrder.audit(inDtoAuditOrder.isApprove(), inDtoAuditOrder.getRejectReason());

        // ====== 存储 =======
        if (ONLY_ONE_SHOULD_BE_UPDATED != orderRepository.updateTradeOrderStatus(tradeOrder)) {
            throw new TradeException("audit fail, updated count != 1");
        }
    }

}
